<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>车辆备案</el-breadcrumb-item>
            <el-breadcrumb-item>非道路移动机械备案</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">修改非道路移动机械备案</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <el-form label-width="110px" label-position="left" style="background: white; padding: 20px" :model="form" ref="ruleFormRef" :rules="rules" scroll-to-error>
          <el-row :gutter="20">
            <el-col v-if="factoryId == 0" :span="8" >
              <el-form-item label="所属工厂"  prop="factory_id"
                            :rules="[{ required: true, message: '请选择所属工厂' }]">
                <el-select v-model="form.factory_id" placeholder="请选择工厂" clearable>
                  <el-option v-for="fa in factory.factorys" :label="fa.factory_name" :key="fa.id" :value="fa.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="margin-left: -10px; margin-right: 10px" label="环保登记编码" prop="environmentalProtectionRegistrationCode">
                <el-input clearable style="width: 220px; margin-left: 10px" v-model="form.environmentalProtectionRegistrationCode" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="margin-left: -10px; margin-right: 10px" label="机械环保代码" prop="mechanicalEnvironmentalProtectionCode">
                <el-input clearable style="width: 220px; margin-left: 10px" v-model="form.mechanicalEnvironmentalProtectionCode" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="机械名称" prop="machineName">
                <el-input clearable style="width: 220px" v-model="form.machineName" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="margin-left: -10px; margin-right: 10px" label="排放阶段" prop="vehicleEmissions" >
                <el-select clearable style="margin-left: 10px;width:220px" v-model="form.vehicleEmissions" placeholder="请选择">
                  <el-option label="国0" value="国0" />
                  <el-option label="国Ⅰ" value="国Ⅰ" />
                  <el-option label="国Ⅱ" value="国Ⅱ" />
                  <el-option label="国Ⅲ" value="国Ⅲ" />
                  <el-option label="国Ⅳ" value="国Ⅳ" />
                  <el-option label="国Ⅴ" value="国Ⅴ" />
                  <el-option label="国Ⅵ" value="国Ⅵ" />
                  <el-option label="新能源" value="新能源" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="发动机号码">
                <el-input clearable style="width: 220px" v-model="form.engineNumber" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="注册日期" prop="registrationDate">
                <el-date-picker clearable v-model="form.registrationDate" type="date" placeholder="请选择"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item style="margin-left: -10px; margin-right: 10px" label="所属企业名称" prop="nameOfAffiliatedEnterprise">
                <el-input clearable style="width: 220px;margin-left:10px" v-model="form.nameOfAffiliatedEnterprise" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运输货物">
                <el-input clearable style="width: 220px" v-model="form.freight" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运输重量/吨">
                <el-input clearable style="width: 220px" v-model="form.transportWeight" class="w-50 m-2" placeholder="请填写"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
             <el-col :span="3" style="margin-left: 25px">
              <div class="UPtsxt"><span>行驶证正本</span></div>
                     <el-upload v-model="form.drivingLicense" class="avatar-uploader" :file-list="state.fileList" action='#'
                        :http-request="uploadAction" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                        :on-remove="handleRemoveLicense" :on-preview="selectLicense" :class="{hide:showUploadLicense}">
                      <el-icon class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>

              </el-col>
            <el-col :span="3" style="margin-left: 25px">
              <div class="UPtsxt"><span>行驶证副本</span></div>

                    <el-upload v-model="form.vehiclePhoto" class="avatar-uploader" :file-list="state.fileListVehicle" action='#'
                        :http-request="uploadvehiclePhoto" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                        :on-remove="handleRemoveVehicle" :on-preview="selectV" :class="{hide:showUploadV}">
                      <el-icon class="avatar-uploader-icon">
                        <Plus />
                      </el-icon>
                    </el-upload>

              </el-col>
                <el-col :span="3" style="margin-left: 25px">
                <div class="UPtsxt"><span>发动机铭牌照片</span></div>

                        <el-upload v-model="form.accompanyingList" class="avatar-uploader" :file-list="state.fileListAcc" action='#'
                            :http-request="uploadAccompanyingList" :limit="1" list-type="picture-card" accept="image/png,image/jpg,image/jpeg"
                            :on-remove="handleRemoveAcc" :on-preview="handlePictureCardPreviewAcc" :class="{hide:showUpload}">
                          <el-icon class="avatar-uploader-icon">
                            <Plus />
                          </el-icon>
                        </el-upload>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20" style="margin: 40px 25px 20px">
              <el-tag class="ml-2" type="danger">图片操作为本地操作,点击添加、删除或预览图片,完成后提交上传数据。</el-tag>
            </el-col>
			 </el-row>
          <el-row>
            <div style="margin: 10px auto 20px">
              <el-col>
                <el-button class="sele-but" @click="update(form)">修改</el-button>
                <el-button class="empty-but" @click="close()">取消</el-button>
              </el-col>
            </div>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
		 <!--行驶证正本查看图片-->
      <el-dialog v-model="drivingLicenseDig" >
        <el-image :src="form.drivingLicense" />
      </el-dialog>
      <!--行驶证副本查看图片-->
      <el-dialog v-model="vehiclePhotoDig" >
        <el-image :src="form.vehiclePhoto" />
      </el-dialog>
      <!--发动机铭牌照片查看图片-->
      <el-dialog v-model="dialogVisible" >
        <el-image :src="form.accompanyingList" />
      </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
//接口
import { updateRoad, uploadImg} from "@/api/mobilePollution";
import { UploadProps } from "element-plus";
// 路由
import { useRouter } from "vue-router";
import { v3ImgPreviewFn } from "v3-img-preview";
import { getFactoryInfo } from "../../../api/factory";
    const router = useRouter();
    // 跳转回列表页
    const close = () => {
      localStorage.removeItem("userObj");
      router.push({
        path: "/nonRoadIndex",
      });
    };
onMounted(() => {
  getFactorys()
})
const factoryId = localStorage.getItem('factoryId')
let factory=reactive({factorys:[],factoryNames:{}});
const getFactorys = ()=>{
  getFactoryInfo({pageSize:1000}).then(res=>{
    let factorys = [];
    res.data?.list.forEach(e=>{
      factorys.push(e);
      factory.factoryNames[e.id]=e;
    })
    factory.factorys = factorys;
  })
}
    //修改按钮
const ruleFormRef = ref()
    const update = () => {
      if (!form) return
      ruleFormRef.value.validate(valid=>{
        if (valid) {
            updateRoad(form).then((res) => {
              if (res.code == 200) {
                localStorage.removeItem("userObj");
                router.push({
                  path: "/nonRoadIndex",
                });
              } else {
                ElMessage.error("保存数据失败");
              }
            });
          }
      })
    }
    let form = reactive(JSON.parse(localStorage.getItem("userObj")));
    const rules = {
      environmentalProtectionRegistrationCode: [
        {
          required: true,
          message: "请填写环保登记编码",
          trigger: "blur",
        },
      ],
      mechanicalEnvironmentalProtectionCode: [
        {
          required: true,
          message: "请填写机械环保代码",
          trigger: "blur",
        },
      ],
      vehicleEmissions: [
        {
          required: true,
          message: "请选择排放阶段",
          trigger: "blur",
        },
      ],
      nameOfAffiliatedEnterprise: [
          {
            required: true,
            message: "请填写所属企业名称",
            trigger: "blur",
          },
        ],
        machineName: [
          {
            required: true,
            message: "请填写机械名称",
            trigger: "blur",
          },
        ],
        registrationDate: [
          {
            required: true,
            message: "请选择注册日期",
            trigger: "change",
          },
        ],
    };

//行驶证(正面)
const  showUploadLicense = ref(true)
const drivingLicenseDig = ref(false)
let sessionDataLicense = reactive(JSON.parse(localStorage.getItem("userObj")).drivingLicense)

const func = function (){
  if(sessionDataLicense){
    showUploadLicense.value=true;
    return [{url:`${process.env.VUE_APP_BASE_API}${'/'}${sessionDataLicense}`}];
  }else{
    showUploadLicense.value=false;
    return [];
  }
};

//车辆照片（正面）
const vehiclePhotoDig = ref(false)
const  showUploadV = ref(true)
let sessionDataVehicle = reactive(JSON.parse(localStorage.getItem("userObj")).vehiclePhoto)
const funcV = function (){
  if(sessionDataVehicle){
    showUploadV.value=true;
    return [{url:`${process.env.VUE_APP_BASE_API}${'/'}${sessionDataVehicle}`}];
  }else{
    showUploadV.value=false;
    return [];
  }
};
//随车清单（正面）
const dialogVisible = ref(false)
const  showUpload = ref(true)
let sessionDataAcc = reactive(JSON.parse(localStorage.getItem("userObj")).accompanyingList)
const funcAcc = function (){
  if(sessionDataAcc){
    showUpload.value=true;
    return [{url:`${process.env.VUE_APP_BASE_API}${'/'}${sessionDataAcc}`}];
  }else{
    showUpload.value=false;
    return [];
  }
};

    const state = reactive({
      bannerUrl: '',
      fileList: func(),
      fileListAcc:funcAcc(),
      fileListVehicle:funcV(),
      fileName: '',
    })
    const handleExceed = (files, fileList) => {
      if (state.fileList.length >= 1) {
        ElMessage.error('只能上传一个图片')
        return;
      }
    }
    const beforeUpload = (file) => {
      const type = ['image/jpeg', 'image/jpg', 'image/png']
      if (type.indexOf(file.type) === -1) {
        ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
        return false
      } else if (file.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
      }
    }

//行驶证正本
const handleRemoveLicense= (uploadFile, uploadFiles) => {
  form.drivingLicense = null
  showUploadLicense.value = false
}
const selectLicense = (uploadFile) => {
  // form.drivingLicense = uploadFile.url
  // drivingLicenseDig.value = true
  v3ImgPreviewFn(uploadFile.url)
}
    const uploadAction = (option) => {
      showUploadLicense.value = true
      let param = new FormData();
      param.append('files', option.file);
      uploadImg(param).then((res) => {
        if (res && res.code === 200) {
          form.drivingLicense = res.data[0]
          // state.fileList = []
          showUploadLicense.value = true
          ElMessage.success('上传成功！');
        }else {
          state.fileList = []
          showUploadLicense.value = false
          ElMessage.error('上传失败,请重试');
        }
      })
    }
    //行驶证副本
const handleRemoveVehicle= (uploadFile, uploadFiles) => {
  form.vehiclePhoto = null
  showUploadV.value = false
}
const selectV = (uploadFile) => {
  // form.vehiclePhoto = uploadFile.url
  // vehiclePhotoDig.value = true
  v3ImgPreviewFn(uploadFile.url)
}

const uploadvehiclePhoto = (option) => {
  showUploadV.value = true
      let param = new FormData();
      param.append('files', option.file);
      uploadImg(param).then((res) => {
        if (res && res.code === 200) {
          form.vehiclePhoto = res.data[0]
          // state.fileListVeicle = []
          showUploadV.value = true
          ElMessage.success('上传成功！');
        }else {
          state.fileListVehicle = []
          showUploadV.value = false
          ElMessage.error('上传失败,请重试');
        }
      })
    }

//随车清单（正面）发动机铭牌照片
const handleRemoveAcc= (uploadFile, uploadFiles) => {
  form.accompanyingList = null
  showUpload.value = false
}
const handlePictureCardPreviewAcc = (uploadFile) => {
  // form.accompanyingList = uploadFile.url
  // dialogVisible.value = true
  v3ImgPreviewFn(uploadFile.url)
}
    const uploadAccompanyingList = (option) => {
      showUpload.value = true
      let param = new FormData();
      param.append('files', option.file);
      uploadImg(param).then((res) => {
        if (res && res.code === 200) {
          form.accompanyingList = res.data[0]
          // state.fileListAcc = []
          showUpload.value = true
          ElMessage.success('上传成功！');
        }else {
          state.fileListAcc = []
          showUpload.value = false
          ElMessage.error('上传失败,请重试');
        }
      })
    }

</script>
<style scoped>
/*超出限制 隐藏图片上传*/
::v-deep.hide .el-upload--picture-card {
  display: none;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 文件上传文字样式 */

.UPtsxt {
  width: 120px;
  height: 30px;
}
/* 文件上传样式 */

.avatar-uploader {
  width: 120px;
  height: 120px;
  background-color: #e5f4ff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #3780b9;
  width: 120px;
  height: 120px;
  text-align: center;
}
.avatar-img{
  width:120px;
  height:120px
}

/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}
</style>
